package com.test.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Result;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.test.common.PingYinUtil;
import com.test.dao.UserDao;
import com.test.model.UserModel;
import com.test.model.WriteModel;
import com.test.model.ZtreeNodes;
import com.test.service.IUserService;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 
 * 用户Controller
 * @author sftwa
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	private final static Log LOGGER = LogFactory.getLog(UserController.class);
	private String prefix = "";
	@Resource
	private UserDao userDao;
	@Resource
	private IUserService userService;
	
/*	@RequestMapping("/getUser1111")
	public void getUser(HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(userDao.getUserId());
	}*/
	@RequestMapping("/insert")
	public String insert(HttpServletResponse response) throws IOException{
		//userDao.insert("2","张三");
		return "System_User/loginUI";
	}
	@RequestMapping("/left")
	public String left(){
		return "left";
	}
	@RequestMapping("/top")
	public String top(){
		return "top";
	}
	@RequestMapping("/right")
	public String right(){
		return "right";
	}
	@RequestMapping("/bottom")
	public String bottom(){
		return "bottom";
	}
	
	/**
	 * 登录
	 */
	@RequestMapping("/login")
	public String login(String loginName,String password,Model model,HttpServletRequest request){
		if(loginName!=null&&password!=null){
			UserModel user = userDao.findUser(loginName,password);
			LOGGER.info("页面用户："+loginName+"   密码："+password);
			LOGGER.info("当前用户："+user);
			if(user.getName()!=null&&!user.getName().equals("")){
				userDao.updateState(loginName,"1");
				request.getSession().setAttribute("user", user);
				LOGGER.info(user.getName() +"  登陆成功");
				return "index";
			}
		}
		return "System_User/loginUI";
	}
	
	/**
	 * 查询树 菜单
	 */
	@RequestMapping("/getztree")
	@ResponseBody
	public List getztree(HttpServletRequest request){
		String currentRole = ((UserModel)request.getSession().getAttribute("user")).getRole();
		List<ZtreeNodes> list = userDao.getztree(currentRole);
		LOGGER.info("查询树:"+list);
		return list;
	}
	
	/**
	 * 授权树
	 * @param request
	 * @return
	 */
	
	@RequestMapping("/getztreeProv")
	@ResponseBody
	public List getztreeProv(HttpServletRequest request){
		//String currentRole = ((UserModel)request.getSession().getAttribute("user")).getRole();
		List<ZtreeNodes> list = userDao.getztreeProv();
		LOGGER.info("查询树:"+list);
		return list;
	}
	/**
	 * 得到登录用户
	 */
	@RequestMapping("/getUser")
	@ResponseBody
	public Object getUser(Model model,HttpServletRequest request){
		return request.getSession().getAttribute("userName");
	}
	/**
	 * 得到在线用户数
	 */
	@RequestMapping("/getAccount")
	@ResponseBody
	public Object getPersonAccount(HttpServletRequest request) {
		int account = userDao.getAccount();
		return account;
	}
	
	@RequestMapping("/mytaskList")
	public String myTaskList(){
		return "Flow_FORMFlow/myTaskList";
	}
	@RequestMapping("/regist")
	public String regist(UserModel user){
		userService.insertOrUpdate(user);
		return "System_User/list";
	}
	@RequestMapping("/logout")
	public String logOut(HttpServletRequest request,String account){
		account = new StringBuffer(PingYinUtil.getPingYin(account)).toString();
		account = ((UserModel)request.getSession().getAttribute("user")).getAccount();
		userDao.updateState(account,"0");
		request.getSession().invalidate();
		LOGGER.info(account+"   退出登陆");
		return "System_User/logout";
	}
	@RequestMapping("/getonline")
	public String getonlone(){
		return "user/online";
	}
	
	@RequestMapping("/getonlineTable")
	@ResponseBody
	public Object getonlineTable(){
		List<WriteModel> list = userDao.getonlineUser();
		return list;
	}
	@RequestMapping("/userlist")
	public String userlist(){
		return "System_User/list";
	}
	@RequestMapping("/getAllUser")
	@ResponseBody
	public Object getAllUser(){
		List<WriteModel> list = userDao.getAllUser();
		return list;
	}
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(String account){
		userDao.delete(account);
		return true;
	}
	@RequestMapping("/edit")
	@ResponseBody
	public Object edit(String account){
		UserModel userModel = userDao.getUserByAccount(account);
		return userModel;
	}
	
	/**
	 * 查询所有的角色
	 */
	@RequestMapping("/getAllRole")
	@ResponseBody
	public Object getAllRole(){
		List<Map<String , Object>> rolesMap = userDao.getAllRole();
		return rolesMap;
	}
	
	/**
	 * 跳转到权限控制页面
	 */
	@RequestMapping("/prove")
	public String prove(){
		return "System_User/prove";
	}
	
	/**
	 * 跳转到个人信息修改页面
	 */
	@RequestMapping("/userInfo")
	public String userInfo(){
		return "Person_Config/editUserInfoUI";
	}
	/**
	 * 跳转到密码修改页面
	 */
	@RequestMapping("/editpasUI")
	public String editPassword(){
		return "Person_Config/editPasswordUI";
	}
	
	/**
	 * 进行授权
	 */
	@RequestMapping("/prov")
	@ResponseBody
	public Object prov(String  menus,String role){
		menus = menus.substring(0, menus.length()-1);
		String arr[] = menus.split(",");
		//删除当前角色的所有权限
		userDao.deleteallProv(role);
		for(int i=0;i<arr.length;i++){
			String id = UUID.randomUUID().toString().replace("-","");
			userDao.prov(id, arr[i], role);
		}
		return true;
	}
	
	/**
	 * 回显当前角色的所有权限
	 */
	@RequestMapping("/provshow")
	@ResponseBody
	public Object proveShow(String role){
		return userDao.proveShow(role);
	}
	
	/**
	 * 上传个人头像
	 * @throws IOException 
	 */
	@PostMapping("/editInfo")
	public String  upload(@RequestParam("image")MultipartFile image,HttpServletRequest request) throws IOException{
		String nameString =System.currentTimeMillis()+image.getOriginalFilename();
		String path = request.getRealPath("");
		 //File file = ResourceUtils.getFile("classpath:image");
		InputStream inputStream = image.getInputStream();
		OutputStream outputStream  = new FileOutputStream(path+"//"+nameString);
		byte [] arr = new byte[1024];
		int len = 0;
		while ((len=inputStream.read(arr))>0) {
			outputStream.write(arr, 0, len);
		}
		UserModel  user = (UserModel)request.getSession().getAttribute("user");
		String userId = user.getId();
		userDao.setImage(path+nameString,userId);
		user.setImgpath(path+nameString);
		request.getSession().setAttribute("user",user);
		outputStream.close();
		inputStream.close();
		return userInfo();
	}
}
